package com.open.capacity.reptile.util;

import com.alibaba.fastjson.JSONObject;
import com.open.capacity.finance.dto.OCRData;
import com.open.capacity.reptile.constant.PurchaseNoticeConstant;
import com.open.capacity.reptile.dto.common.ResponseWithCookies;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class VerifyCodeUtils {

    public static String getVerifyCode(String url, String localFilePath) {
//        File imageFile = new File("D:\\verifyCode.png");
//        Tesseract tesseract = new Tesseract();
//        tesseract.setDatapath("d:\\tessdata");
//        String result = "";
//        try {
//            result = tesseract.doOCR(imageFile);
//            System.out.println(result);
//        } catch (Exception e) {
//
//        }
//        return result;

        Map<String, String> params = new HashMap<String, String>();
        String q = loadAsBase64(url, localFilePath);
        String salt = String.valueOf(System.currentTimeMillis());
        String detectType = "10012";
        String imageType = "1";
        String langType = "ar";
        params.put("detectType", detectType);
        params.put("imageType", imageType);
        params.put("langType", langType);
        params.put("img", q);
        params.put("docType", "json");
        params.put("signType", "v3");
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        params.put("curtime", curtime);
        String signStr = PurchaseNoticeConstant.APP_KEY + truncate(q) + salt + curtime + PurchaseNoticeConstant.APP_SECRET;
        String sign = getDigest(signStr);
        params.put("appKey", PurchaseNoticeConstant.APP_KEY);
        params.put("salt", salt);
        params.put("sign", sign);
        ResponseWithCookies result = null;
        try {
            result = HttpUtils.requestForPost(PurchaseNoticeConstant.YOUDAO_URL, params,null);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        /** 处理结果 */

        OCRData ocrData = JSONObject.parseObject(result.getContent(), OCRData.class);
        System.out.println(ocrData.getResult().getRegions().get(0).getLines().get(0).getText());
        return ocrData.getResult().getRegions().get(0).getLines().get(0).getText();
    }

    /**
     * 生成加密字段
     */
    private static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes();
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 加载Base64图片
     *
     * @param url
     * @return
     */
    private static String loadAsBase64(String url, String localFilePath) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        HttpUtils.downloadFileFromUrl(url, localFilePath + "/verfify.gif");
        File file = new File(localFilePath + "/verfify.gif");
        if (!file.exists()) {
            log.error("文件不存在");
            return null;
        }
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return Base64.getEncoder().encodeToString(data);//返回Base64编码过的字节数组字符串
    }

    private static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }
}
